package com.agent.history.controller;


import com.agent.commons.Result.Result;
import com.agent.commons.exception.BaseException;
import com.agent.commons.utils.JacksonUtil;
import com.agent.history.service.ConversationService;
import com.agent.history.vo.ConversationListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.agent.commons.errorcode.ServiceErrorCodeConstants.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.agent.commons.constants.RedisConstants.*;

@Slf4j
@RestController
@RequestMapping("/conversation")
public class    ConversationController {

    @Autowired
    private ConversationService conversationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/check")
    public boolean checkConversationIdWithUserId(String userId,String conversationId){
        return conversationService.checkConversationIdWithUserId(userId,conversationId);
    }


    /**
     * 获取会话列表
     * @param userId
     * @return
     */
    @GetMapping("/get/conversationList/{userId}")
    public Result<List<ConversationListVO>> getConversationId(@PathVariable String userId){
        //判断用户是否存在
        if(!conversationService.checkUserExist(userId)) {
            throw new BaseException(USER_NOT_EXIST);
        }
        List<ConversationListVO> conversationListVOList=new ArrayList<>();
        if(!conversationService.getConversationListVOFromRedis(userId).isEmpty()){
            //如果有则直接返回
            log.info("从Redis中获取会话列表成功！");
            conversationListVOList=conversationService.getConversationListVOFromRedis(userId);
        }else{
            log.info("从数据库中获取会话列表！");
            // 如果没有则从数据库中获取
            conversationListVOList= conversationService.getConversationMember(userId).stream()
                    .map(e->{
                        ConversationListVO conversationListVO=new ConversationListVO();
                        BeanUtils.copyProperties(e,conversationListVO);
                        return conversationListVO;
                    }).toList();
            //如果该用户有数据记录，则重新提交到redis
            if(!conversationListVOList.isEmpty()) {
                Set<ZSetOperations.TypedTuple<String>> lists=new HashSet<>();
                //遍历会话列表
                for (ConversationListVO e : conversationListVOList) {
                    //创建时间戳
                    long timestamp = System.nanoTime();
                    //创建ZSetOperations.TypedTuple对象
                    ZSetOperations.TypedTuple<String> tuple = ZSetOperations.TypedTuple.of(JacksonUtil.writeValueAsString(e), (double) timestamp);
                    //添加到ZSetOperations.TypedTuple对象中
                    lists.add(tuple);
                }
                //添加到Redis中
                stringRedisTemplate.opsForZSet().add(MESSAGE_HISTORY + userId, lists);
                //设置过期时间
                stringRedisTemplate.expire(MESSAGE_HISTORY + userId, 7, TimeUnit.DAYS);
            }else{
                log.error("用户没有会话记录！");
            }
        }
        return Result.success(conversationListVOList);
    }

}
